//
//  NetworkAPI.m
//  ACE
//
//  Created by Mickey Yin on 2021/12/4.
//

#import "NetworkAPI.h"
#import "AFNetworking.h"

static AFHTTPSessionManager const *manager;

@implementation NetworkAPI

+(void)load {
    manager = [AFHTTPSessionManager manager];
}

+(void)getWithURLString:(NSString *)url params:(NSDictionary *)params success:(HttpSuccess)success failure:(HttpFailure)failure {
    
    [self requestHttpsRequestUrl:@"GET" requestUrl:url requestBody:params requestHeader:nil success:success failuer:failure];
}

+(void)postWithURLString:(NSString *)url params:(NSDictionary *_Nonnull)params success:(HttpSuccess)success failure:(HttpFailure)failure {
    
    [self requestHttpsRequestUrl:@"POST" requestUrl:url requestBody:params requestHeader:nil success:success failuer:failure];
}

+(void)postHeaderWithURLString:(NSString *)url params:(NSDictionary *)params header:(NSDictionary *)header success:(HttpSuccess)success failure:(HttpFailure)failure {
    
    [self requestHttpsRequestUrl:@"POST" requestUrl:url requestBody:params requestHeader:header success:success failuer:failure];
}

+(void)requestHttpsRequestUrl:(NSString *)method requestUrl:(NSString *)url requestBody:(NSDictionary *)body requestHeader:(NSDictionary *)header success:(HttpSuccess)success failuer:(HttpFailure)failure {
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.requestSerializer.timeoutInterval = 15;
    
    for (NSString *key in header) {
        //调出请求头
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        //将token封装入请求头
        [manager.requestSerializer setValue:header[key] forHTTPHeaderField:key];
    }
    manager.securityPolicy.allowInvalidCertificates = YES;
    manager.securityPolicy.validatesDomainName = NO;
   
    if ([method isEqualToString:@"GET"]) {
        [manager GET:url parameters:body headers:header progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
#if DEBUG
            NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            NSLog(@"网络请求回来的字符串 str= %@ \n\n url= %@   \n params = %@", str,url,body);
#endif
            id json = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            
            if (success) {
                success(json);
            }
                
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            if (failure) {
                failure(error);
            }
        }];
        
    } else {
        
        [manager POST:url parameters:body headers:header progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
#if DEBUG
            NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            NSLog(@"网络请求回来的字符串 str= %@\nurl = %@   \n params = %@", str,url,body);
#endif
            id json = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            
            if (success) {
                success(json);
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (failure) {
                failure(error);
            }
        }];
    }
    
}

// 异步方法
- (void)requestSync:(NSString *)bodyString bankId:(NSString *)bankId channelId:(NSString *)channelId successBlock:(ifaaMsgToServerSuccess)successBlock errorBlock:(ifaaMsgToServerError)errorBlock
{
    self.successBlock = successBlock;
    self.errorBlock = errorBlock;
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:_nsURL
                                                     cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                  timeoutInterval:10];
    //POST请求
    [request setHTTPMethod:@"POST"];
    //把bodyString转换为NSData数据
    NSString *jsonStr = bodyString;
    NSData *bodyData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    
    //请求头
    [request setValue:@"application/json" forHTTPHeaderField:@"content-type"];//这个很关键，一定要设置
    [request setValue:@"UTF-8" forHTTPHeaderField:@"Charset"];
    [request setValue:bankId forHTTPHeaderField:@"_bankId"];
    [request setValue:channelId forHTTPHeaderField:@"_channelId"];
    
    //body 数据
    [request setHTTPBody:bodyData];
    
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            self.successBlock(NO, error.description);
        }else {
            NSString * resultStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            self.successBlock(YES, resultStr);
        }
    }];
    
    [dataTask resume];
}


// 为了方便把流程说清楚，这里用了同步方法，在接入的时候兼用用异步方式实现。
- (NSString *) requestSync:(NSString *)bodyString
{
    NSString* resultStr = nil;
    NSMutableURLRequest *nsMutableURLRequest = [NSMutableURLRequest requestWithURL:_nsURL
                                                                       cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                                   timeoutInterval:10];
    //POST请求
    [nsMutableURLRequest setHTTPMethod:@"POST"];
    //把bodyString转换为NSData数据
    NSData *bodyData =  [bodyString dataUsingEncoding:NSUTF8StringEncoding];
    //请求头
    [nsMutableURLRequest setValue:@"application/json" forHTTPHeaderField:@"content-type"];
    
    [nsMutableURLRequest setValue:@"UTF-8" forHTTPHeaderField:@"Charset"];
    //body 数据
    [nsMutableURLRequest setHTTPBody:bodyData];
    
    NSURLResponse * response = nil;
    NSError * connectionError = nil;
    NSData * data = [NSURLConnection sendSynchronousRequest:nsMutableURLRequest
                                          returningResponse:&response
                                                      error:&connectionError];
    if (!connectionError) {
        
        NSLog(@"%@", [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
        NSLog(@"%@", connectionError);
    }
    resultStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return resultStr;
}


@end
